package com.ruoyi.tj.controller;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.tj.BizError;
import com.ruoyi.tj.entity.Photograph;
import com.ruoyi.tj.entity.ZfZhufangtijianxinxi;
import com.ruoyi.tj.service.PhotographService;
import com.ruoyi.tj.service.ZfZhufangtijianxinxiService;
import com.ruoyi.tj.vo.BizQueryParam;
import com.ruoyi.tj.vo.HouseTijianInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 住房-住房体检信息 前端控制器
 * </p>
 *
 * @author aoliao
 * @since 2024-03-16
 */
@Slf4j
@RestController
@RequestMapping("/api/zf-zhufangtijianxinxi")
public class ZfZhufangtijianxinxiController {


    @Resource
    private ZfZhufangtijianxinxiService service;

    @Resource
    private ISysDictDataService dictDataService;

    @Resource
    private PhotographService photographService;

    /*@PostMapping("/save1")
    @ResponseBody
    public AjaxResult saveRecord(@RequestBody ZfZhufangtijianxinxi record) {
        try {
            record = service.saveRecord(record);
            return AjaxResult.success((Object) record.getId());
        } catch (Throwable e) {
            log.error("saveRecord 异常", e);
            return AjaxResult.error(e.getMessage());
        }
    }*/


    @PostMapping("/save")
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Throwable.class)
    public AjaxResult saveRecord(@RequestBody HouseTijianInfoVO recordVo) {

        ZfZhufangtijianxinxi record = new ZfZhufangtijianxinxi();
        BeanUtils.copyProperties(recordVo, record);
        List<Photograph> images = recordVo.getImages();
        SysUser user = ShiroUtils.getSysUser();
        try {
            // 只有新增时才设置楼栋id
            if(StringUtils.isEmpty(record.getId()) && StringUtils.isEmpty(record.getLoudongId())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error(BizError.MISS_PARAM + "loudongId");
            }

            // 只有新增时才设置小区id
            if(StringUtils.isEmpty(record.getId()) && record.getXiaoquId() == null) {
                record.setXiaoquId(user.getDeptId());
            }

            // 从数据库读取dict_code
            Long dictCode = dictDataService.selectDictCode(record.getDictType(), record.getDictValue());
            record.setDictCode(dictCode);

            record = service.saveRecord(record);
            if(images != null && images.size() > 0) {
                String id = record.getId();
                for (Photograph image : images) {
                    image.setId(null);
                    image.setInfoId(id);
                }
            }
            photographService.deleteByInfoId(record.getId());
            if(images != null && images.size() > 0) {
                photographService.saveRecordBath(images);
            }
            return AjaxResult.success((Object)record.getId());
        } catch (Throwable e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("saveRecord 异常", e);
            return AjaxResult.error(e.getMessage());
        }

    }

    @PostMapping("/saveBatch")
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Throwable.class)
    public AjaxResult saveRecordBath(@RequestBody List<HouseTijianInfoVO> recordsVo) {
        List<String> ids = new ArrayList<>();
        SysUser user = ShiroUtils.getSysUser();
        for (HouseTijianInfoVO recordVo : recordsVo) {
            ZfZhufangtijianxinxi record = new ZfZhufangtijianxinxi();
            BeanUtils.copyProperties(recordVo, record);
            List<Photograph> images = recordVo.getImages();
            try {
                // 只有新增时才设置楼栋id
                if(StringUtils.isEmpty(record.getId()) && StringUtils.isEmpty(record.getLoudongId())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error(BizError.MISS_PARAM + "loudongId");
                }

                // 只有新增时才设置小区id
                if(StringUtils.isEmpty(record.getId()) && record.getXiaoquId() == null) {
                    record.setXiaoquId(user.getDeptId());
                }

                // 从数据库读取dict_code
                Long dictCode = dictDataService.selectDictCode(record.getDictType(), record.getDictValue());
                record.setDictCode(dictCode);

                record = service.saveRecord(record);
                if(images != null && images.size() > 0) {
                    String id = record.getId();
                    for (Photograph image : images) {
                        image.setId(null);
                        image.setInfoId(id);
                    }
                }
                photographService.deleteByInfoId(record.getId());
                if(images != null && images.size() > 0) {
                    photographService.saveRecordBath(images);
                }
                ids.add(record.getId());
            } catch (Throwable e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                log.error("saveRecord 异常", e);
                return AjaxResult.error(e.getMessage());
            }
        }
        return AjaxResult.success(ids);
    }

    @PostMapping("/get")
    @ResponseBody
    public AjaxResult getRecord(@RequestBody ZfZhufangtijianxinxi record, @RequestBody(required = false) BizQueryParam params) {
        ZfZhufangtijianxinxi record1 = service.getRecord(record, params);
        if(record1 == null) {
            return AjaxResult.success((Object) "");
        }
        List<Photograph> photographs = photographService.selectByInfoId(record1.getId());
        HouseTijianInfoVO houseTijianInfoVO=  new HouseTijianInfoVO();
        BeanUtils.copyProperties(record1, houseTijianInfoVO);
        houseTijianInfoVO.setImages(photographs);
        // return record1 != null ? AjaxResult.success(record1) : AjaxResult.success((Object) "");
        return AjaxResult.success(houseTijianInfoVO);
    }

    @PostMapping("/get/{id}")
    @ResponseBody
    public AjaxResult getRecord(@PathVariable("id") String id) {
        ZfZhufangtijianxinxi record1 = service.getRecordById(id);
        if(record1 == null) {
            AjaxResult.success((Object) "");
        }
        List<Photograph> photographs = photographService.selectByInfoId(record1.getId());

        HouseTijianInfoVO houseTijianInfoVO=  new HouseTijianInfoVO();
        BeanUtils.copyProperties(record1, houseTijianInfoVO);
        houseTijianInfoVO.setImages(photographs);
        /*if(record1 != null) {
            SysDictData sysDictData = dictDataService.selectDictDataById(record1.getDictCode());
            record1.setDictData(sysDictData);
        }*/
        return AjaxResult.success(houseTijianInfoVO);
    }

    @PostMapping("/listPage")
    @ResponseBody
    public AjaxResult listPage(@RequestBody ZfZhufangtijianxinxi record, @RequestBody(required = false) BizQueryParam params) {
        String type = record.getType();
        IPage<ZfZhufangtijianxinxi> iPage = StringUtils.isNotEmpty(type) ? service.listPageByType(type, record, params) : service.listPage(record, params);
        List<ZfZhufangtijianxinxi> records = iPage.getRecords();
        if(records != null && records.size() > 0) {
            List<String> ids = records.stream().map(ZfZhufangtijianxinxi::getId).collect(Collectors.toList());
            List<Photograph> photographs = photographService.selectByInfoIds(ids);
            Map<String, List<Photograph>> photoMap = new HashMap<>();
            for (Photograph photograph : photographs) {
                List<Photograph> images = photoMap.getOrDefault(photograph.getInfoId(), new ArrayList<>());
                images.add(photograph);
                photoMap.put(photograph.getInfoId(), images);
            }
            IPage<HouseTijianInfoVO> pageObj = new Page<>();
            List<HouseTijianInfoVO> pageRecords = new ArrayList<>();
            for (ZfZhufangtijianxinxi rec : records) {
                HouseTijianInfoVO houseTijianInfoVO=  new HouseTijianInfoVO();
                BeanUtils.copyProperties(rec, houseTijianInfoVO);
                List<Photograph> images = photoMap.getOrDefault(rec.getId(),new ArrayList<>());
                houseTijianInfoVO.setImages(images);
                pageRecords.add(houseTijianInfoVO);
            }
            pageObj.setRecords(pageRecords);
            pageObj.setPages(iPage.getPages());
            pageObj.setCurrent(iPage.getCurrent());
            pageObj.setSize(iPage.getSize());
            pageObj.setTotal(iPage.getTotal());
            return AjaxResult.success(pageObj);
        } else {
            return AjaxResult.success(iPage);
        }
    }

    @PostMapping("/delete/{id}")
    @ResponseBody
    public AjaxResult deleteById(@PathVariable("id") String id) {
        service.deleteRecordById(id);
        photographService.deleteByInfoId(id);
        return AjaxResult.success();
    }


    @PostMapping("/delete")
    @ResponseBody
    public AjaxResult deleteByIds(@RequestBody String[] ids) {
        //String[] split = ids.split(",");
        service.deleteRecordByIds(Arrays.asList(ids));
        photographService.deleteRecordByIds(Arrays.asList(ids));
        return AjaxResult.success();
    }

}
